
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:webview_flutter/webview_flutter.dart';
/// 加载 h5
class DDWebViewPage extends StatefulWidget {
  final String url;
  final String? title;

  const DDWebViewPage({super.key, required this.url, this.title});

  @override
  DDWebViewPageState createState() => DDWebViewPageState(url, title);
}

class DDWebViewPageState extends State<DDWebViewPage> {
  final String url;
  String? title;
  WebViewController? _webViewController;

  DDWebViewPageState(this.url, this.title);

  @override
  void initState() {
    super.initState();
    // Enable hybrid composition.
    if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios_new),
            onPressed: () {
              navigator?.pop();
            },
          ),
          //backgroundColor: Colors.black,
          centerTitle: true,
          elevation: 0,
          title: Text(title ?? '',style: TextStyle(fontSize: 17 ,color: Colors.black87,fontWeight: FontWeight.w700)),
        ),
        body: Column(children: [
          Expanded(
            child: WebView(
              initialUrl: url,
              javascriptMode: JavascriptMode.unrestricted,
              allowsInlineMediaPlayback: true,
              backgroundColor: Colors.white,
              initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow,
              onWebViewCreated: (controller) {
                _webViewController = controller;
              },
              onPageStarted: (v) {},
              onPageFinished: (v) async {
                if(title == null) {
                  await getTitle();
                }
              },
              onWebResourceError: (WebResourceError error) {
                _webViewController?.reload();
              },
            ),
          )
        ]));
  }

  Future<void> getTitle() async {
    title = await _webViewController?.getTitle();
    setState(() {});
  }
}
